package com.excel.view;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import com.excel.KeyWordSeacher;
import com.excel.SampleKeyWorkdSearcher;
import com.excel.model.ExcelData;

public class ExcelKeywordSearchPanel extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private final JButton button;
	private final JLabel label;
	private final JTable table;
	private final JTextField field;
	private final JTextField searchField;
	private final JButton searchButton;
	public static final int HEIGHT_UNIT = 100;
	public static final int WEIGHT_UNIT = 100;
	private File currentFile = null;
	private static final TableModel  DEFAULT_MODEL = new DefaultTableModel(26, 5);

	private ExecutorService executors = Executors.newFixedThreadPool(Runtime
			.getRuntime().availableProcessors() * 2 + 1);
	private Future<KeyWordSeacher> searcherFuture;

	public ExcelKeywordSearchPanel() {
		this("");
	}

	public ExcelKeywordSearchPanel(String name) {
		this.button = new JButton("打开");
		this.label = new JLabel();
		this.table = new JTable();
		this.label.setText("路径 :");
		this.field = new JTextField(20);
		this.searchButton = new JButton("搜索");
		this.searchButton.setEnabled(false);
		this.searchField = new JTextField(20);
		this.searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Future<KeyWordSeacher> future = ExcelKeywordSearchPanel.this.searcherFuture;
				String text = ExcelKeywordSearchPanel.this.searchField.getText();
				JTable table = ExcelKeywordSearchPanel.this.table;
				ExcelData excelData = null;
				if(future!=null&&text!=null){
					try {
						excelData = future.get().search(text);
					} catch (InterruptedException e1) {
						throw new RuntimeException(e1);
					} catch (ExecutionException e1) {
						throw new RuntimeException(e1);
					}
				}

				if(excelData == null ||excelData.getColumnCount()==0){
					table.setModel(DEFAULT_MODEL);
				}else{
					Vector<Vector<Object>> data = excelData.getData();
					System.out.println("数据长度 ： "+data.size());
					DefaultTableModel model = new DefaultTableModel(data.size(),excelData.getColumnCount());
					int rowCount = 0;
					for(Vector<Object> v :data){
						model.insertRow(rowCount, v);
						rowCount++;
					}
					table.setModel(model);
				}
				table.repaint();
//			    table.updateUI();
			    
			    System.out.println(String.format("table row count %d",table.getRowCount()));
			    System.out.println(String.format("table column count %d",table.getColumnCount()));
			}
		});
		this.table.setModel(DEFAULT_MODEL);
		this.setName(name);
		this.setTitle(this.getName());
		this.init();
	}

	private void init() {
		setSize(492, 534);
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize(); // 系统对象获取工具
		int width = screenSize.width;
		int height = screenSize.height;
		int x = (width - this.getWidth()) / 2;
		int y = (height - this.getHeight()) / 2;
		setLocation(x, y);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		setResizable(false);
		addComponent();
		pack();
	}

	private void addComponent() {

		field.setEditable(false);
		button.addActionListener(this);
		GridBagLayout layout = new GridBagLayout();
		this.setLayout(layout);
		this.add(button);
		this.add(label);
		this.add(field);
		JScrollPane panel = new JScrollPane(table);
		this.add(panel);
		this.add(searchButton);
		this.add(searchField);

		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets(5, 10, 5, 10);
		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridx = 0;
		constraints.gridy = 0;
		layout.setConstraints(label, constraints);

		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridx = 1;
		constraints.gridy = 0;
		layout.setConstraints(field, constraints);

		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridx = 2;
		constraints.gridy = 0;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		layout.setConstraints(button, constraints);

		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridx = 1;
		constraints.gridy = 1;
		constraints.gridwidth=1;
		layout.setConstraints(searchField, constraints);
		
		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridx = 2;
		constraints.gridy = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		layout.setConstraints(searchButton, constraints);
		
		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridx = 0;
		constraints.gridy = 2;
		layout.setConstraints(panel, constraints);
	}

	public void actionPerformed(ActionEvent e) {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return null;
			}

			@Override
			public boolean accept(File f) {
				return f.getAbsolutePath().endsWith(".xls")
						|| f.getAbsolutePath().endsWith(".xlsx");
			}
		});

		fileChooser.showDialog(new JLabel(), "选择");
		final File file = fileChooser.getSelectedFile();
		if (file != currentFile) {
			this.currentFile = file;
			this.field.setText(file.getAbsolutePath());
			this.searchButton.setEnabled(true);
			this.searcherFuture = executors.submit(new Callable<KeyWordSeacher>() {
				public KeyWordSeacher call() throws Exception {
					return new SampleKeyWorkdSearcher(file.getAbsolutePath());
				}
			});
		}
	}
}
